package com.mybed.crm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mybed.crm.anno.Log;
import com.mybed.crm.common.enums.HttpCodeEnum;
import com.mybed.crm.exception.BaseException;
import com.mybed.crm.pojo.dto.*;
import com.mybed.crm.pojo.pojo.Dict;
import com.mybed.crm.pojo.pojo.DictDetail;
import com.mybed.crm.pojo.pojo.User;
import com.mybed.crm.result.PageResult;
import com.mybed.crm.result.Result;
import com.mybed.crm.result.ResultP;
import com.mybed.crm.service.DictDetailService;
import com.mybed.crm.service.DictService;
import com.mybed.crm.service.UserService;
import com.mybed.crm.utils.thread.UserThreadLocalUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统->字典相关的控制层
 */
@RestController
@RequestMapping("/system/dict")
@Slf4j
@Transactional
public class DictContorller {
    @Autowired
    private DictService dictService;
    @Autowired
    private UserService userService;
    @Autowired
    private DictDetailService dictDetailService;
    /**
     * 分页查询字典类型
     * @param dto
     * @return
     */
    @GetMapping("/type/list")
    public PageResult PageDictQuery(PageDictDto dto){
        LambdaQueryWrapper<Dict> wrapper=new LambdaQueryWrapper();
        wrapper.like(StringUtils.hasLength(dto.getDictName()),Dict::getDictName,dto.getDictName());
        wrapper.like(StringUtils.hasLength(dto.getDictType()),Dict::getDictType,dto.getDictType());
        wrapper.eq(dto.getStatus()!=null,Dict::getStatus,dto.getStatus());
        if(dto.getParams()!=null){
            wrapper.between(StringUtils.hasLength(dto.getParams().get("beginTime"))&&StringUtils.hasLength(dto.getParams().get("endTime")),Dict::getCreateTime,dto.getParams().get("beginTime"),dto.getParams().get("endTime"));
        }
        IPage<Dict> page=new Page<>(dto.getPageNum(),dto.getPageSize());
        IPage<Dict> iPage = dictService.page(page,wrapper);
        PageResult result=new PageResult();
        result.insertData(iPage);
        return result;
    }

    /**
     * 新增字典类型
     * @param dto
     * @return
     */
    @Log("新增字典类型")
    @PostMapping("/type")
    public ResultP addDictType(@RequestBody DictDto dto){
        log.info("新增字典,{}",dto);
        Dict one = dictService.getOne(Wrappers.<Dict>lambdaQuery().eq(Dict::getDictType, dto.getDictType()).or().eq(Dict::getDictName, dto.getDictName()));
        if(one!=null){
            return ResultP.error("类型或名字已经存在");
        }
        Dict dict=new Dict();
        String userId = UserThreadLocalUtil.getUser();
        User user = userService.getById(userId);
        dict.setCreateBy(user.getUserName());
        BeanUtils.copyProperties(dto,dict);
        dict.setCreateTime(LocalDateTime.now());
        dictService.save(dict);
        return ResultP.success();
    }
    /**
     * 通过id查询类型
     */
    @GetMapping("/type/{typeId}")
    public Result getTypeById(@PathVariable String typeId){
        Dict dict = dictService.getById(typeId);
        return Result.success(dict);
    }

    /**
     * 通过字典类型查询字典详情
     * @param typeName
     * @return
     */
    @GetMapping("/data/type/{typeName}")
    public Result getDictDetailByName(@PathVariable String typeName){
        List<DictDetail> detail = dictDetailService.list(Wrappers.<DictDetail>lambdaQuery().eq(DictDetail::getDictType, typeName));
        Result result=new Result();
        result.setCode(HttpCodeEnum.SUCCESS.getCode());
        result.setMsg(HttpCodeEnum.SUCCESS.getErrorMessage());
        result.setData(detail);
        return result;
    }

    /**
     * 字典详情分页查询
     * @param dto
     * @return
     */
    @GetMapping("/data/list")
    public PageResult DictDetail(PageDictDetailDto dto){
        LambdaQueryWrapper<DictDetail> wrapper=new LambdaQueryWrapper();
        IPage<DictDetail> page=new Page<>(dto.getPageNum(),dto.getPageSize());
        if(StringUtils.hasLength(dto.getDictLabel())){
            wrapper.like(DictDetail::getDictLabel,dto.getDictLabel());
        }
        if(StringUtils.hasLength(dto.getDictType())){
            wrapper.eq(DictDetail::getDictType,dto.getDictType());
        }
        wrapper.eq(dto.getStatus()!=null,DictDetail::getStatus,dto.getStatus());
        IPage<DictDetail> iPage = dictDetailService.page(page, wrapper);
        PageResult result=new PageResult();
        result.insertData(iPage);
        return result;
    }

    /**
     * 新增字典详情
     * @param dto
     * @return
     */
    @Log("新增字典详情")
    @PostMapping("/data")
    public ResultP addDictDetailDto(@RequestBody DictDetailDto dto){
        DictDetail detail=new DictDetail();
        String userId = UserThreadLocalUtil.getUser();
        User user = userService.getById(userId);
        BeanUtils.copyProperties(dto,detail);
        detail.setCreateBy(user.getUserName());
        detail.setCreateTime(LocalDateTime.now());
        dictDetailService.save(detail);
        return ResultP.success();
    }

    /**
     * 批量删除字典详情
     * @param ids
     * @return
     */
    @Log("批量删除字典详情")
    @DeleteMapping("/data/{ids}")
    public ResultP deleteDataByIds(@PathVariable String ids){
        List<String> list = Arrays.asList(ids.split(","));
        dictDetailService.removeByIds(list);
        return ResultP.success();
    }

    /**
     * 批量删除字典类型
     * @param ids
     * @return
     */
    @Log("批量删除字典类型")
    @DeleteMapping("/type/{ids}")
    public ResultP deleteTypeByIds(@PathVariable String ids){
        List<String> list = Arrays.asList(ids.split(","));
        List<Dict> dicts = dictService.listByIds(list);
        dicts.forEach(o->{
            DictDetail one = dictDetailService.getOne(Wrappers.<DictDetail>lambdaQuery().eq(DictDetail::getDictType, o.getDictType()));
            if(one!=null){
                throw new BaseException(o.getDictId()+"存在字典详细无法删除");
            }
        });
        dictService.removeByIds(list);
        return ResultP.success();
    }

    /**
     * 修改字典
     * @param dict
     * @return
     */
    @Log("修改字典")
    @PutMapping("/type")
    public ResultP updateType(@RequestBody Dict dict){
        User user = userService.getById(UserThreadLocalUtil.getUser());
        dict.setUpdateBy(user.getUserName());
        dict.setUpdateTime(LocalDateTime.now());
        Dict byId = dictService.getById(dict.getDictId());
        dictService.updateById(dict);
        List<DictDetail> dictDetails = dictDetailService.list(Wrappers.<DictDetail>lambdaQuery().eq(DictDetail::getDictType, byId.getDictType()));
        if(!CollectionUtils.isEmpty(dictDetails)){
            List<DictDetail> collect = dictDetails.stream().map(o -> {
                o.setUpdateTime(LocalDateTime.now());
                o.setUpdateBy(UserThreadLocalUtil.getUser());
                o.setDictType(dict.getDictType());
                return o;
            }).collect(Collectors.toList());
            dictDetailService.updateBatchById(collect);
        }
        return ResultP.success();
    }
    /**
     * 清理缓存
     */
    @DeleteMapping("/type/clearCache")
    public ResultP clearCache(){
        return ResultP.success();
    }
    /**
     * 修改字典详情
     *
     * @return
     */
    @Log("修改字典详情")
    @PutMapping("/data")
    public ResultP updateDetail(@RequestBody DictDetail dictDetail){
        User user = userService.getById(UserThreadLocalUtil.getUser());
        dictDetail.setUpdateBy(user.getUserName());
        dictDetail.setUpdateTime(LocalDateTime.now());
        dictDetailService.updateById(dictDetail);
        return ResultP.success();
    }

    /**
     * 查询单个字典详情
     * @param id
     * @return
     */
    @GetMapping("data/{id}")
    public Result slelectDetailById(@PathVariable String id){
        DictDetail detail = dictDetailService.getById(id);
        return Result.success(detail);
    }


}
